#include <iostream>
#include <cstring>
#include <cerrno>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Thread.hpp"
#include "err.hpp"

const int BUF_SIZE = 1024;

void Usage()
{
    std::cout << "Please enter the correct format: " << std::endl
              << "      ./client [server's ip] [server's port]" << std::endl;
}

struct ThreadData
{
    ThreadData(int sockfd, struct sockaddr_in *psvr) : _sockfd(sockfd), _psvr(psvr)
    {
    }
    int _sockfd;
    struct sockaddr_in *_psvr;
};

void *SendThreadRountine(void *args)
{
    ThreadData *td = static_cast<ThreadData *>(args);
    while (true)
    {
        // 1. 用户输入消息
        std::string message;
        std::cout << "Please Enter# ";
        std::getline(std::cin, message);
        // 2. 发送消息到服务端
        ssize_t n = sendto(td->_sockfd, message.c_str(), message.size(), 0, (struct sockaddr *)td->_psvr, sizeof(*td->_psvr));
        if (n < 0)
        {
            std::cerr << "send error: " << strerror(errno) << std::endl;
            exit(SEND_ERR);
        }
    }
    delete td;
    return nullptr;
}

void *RecvThreadRountine(void *args)
{
    ThreadData *td = static_cast<ThreadData *>(args);
    while (true)
    {
        // 接收其它客户端的消息（来自服务端）
        char buf[BUF_SIZE];
        memset(buf, 0, sizeof(buf));
        struct sockaddr_in tmp;
        bzero(&tmp, sizeof(tmp));
        socklen_t len = sizeof(tmp);

        ssize_t n = recvfrom(td->_sockfd, buf, sizeof(buf) - 1, 0, (struct sockaddr *)&tmp, &len);
        if (n < 0)
        {
            std::cerr << "recv error: " << strerror(errno) << std::endl;
            exit(RECV_ERR);
        }
        buf[n] = '\0';

        // 群聊信息打印到2号文件描述符上，方便重定向观察输出结果
        std::cerr << buf << std::endl;
    }
    delete td;
    return nullptr;
}

// ./client [server's ip] [server's port]
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage();
        exit(USAGE_ERR);
    }

    // 1. 创建套接字
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        std::cerr << strerror(errno) << std::endl;
        exit(SOCKET_ERR);
    }
    // IP和端口号由OS自动分配绑定

    // 2. 获取服务端ip和port
    std::string server_ip = argv[1];
    uint16_t server_port = atoi(argv[2]);

    // 指明服务端的地址族(ip and port)
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(server_port);
    server.sin_addr.s_addr = inet_addr(server_ip.c_str());

    // 一个线程负责让用户输入并发送消息，一个线程负责接收群聊服务器的消息
    Thread send_thread(1, SendThreadRountine, new ThreadData(sockfd, &server));
    Thread recv_thread(2, RecvThreadRountine, new ThreadData(sockfd, &server));

    send_thread.run();
    recv_thread.run();

    send_thread.join();
    recv_thread.join();
    return 0;
}
